<?php

namespace Beerus\Modules\Peanut\Actions;

use Doctrine\DBAL\Exception;
use Doraemon\model\SellGoods\SellGoodsAccountInfo;
use Doraemon\model\SellGoods\SellGoodsBackOrder;
use Doraemon\model\SellGoods\SellGoodsTransferRecord;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;

class UndoTransferRecord extends RowAction
{
    public $name = '撤销操作';
    const TOAST_ALERT = "是否确认撤销操作";

    public function handle($id)
    {
        $transfer_record = SellGoodsTransferRecord::get('*', ['id' => $id]);
        if ($transfer_record && in_array($transfer_record['data_status'], [SellGoodsTransferRecord::DATA_STATUS_SUCCESS, SellGoodsTransferRecord::DATA_STATUS_FAIL])) {
            try {
                $order_ids = explode(',', $transfer_record['order_ids']);
                SellGoodsBackOrder::action(function () use ($order_ids, $transfer_record, $id) {
                    $res = SellGoodsBackOrder::update(['data_status' => SellGoodsBackOrder::TRANSFER_WAIT], ['id' => $order_ids]);
                    if (!$res) throw new Exception('操作失败');
                    $res_tr = SellGoodsTransferRecord::update(['data_status' => SellGoodsTransferRecord::DATA_STATUS_UNDO, 'deleted_at' => time()], ['id' => $id]);
                    if (!$res_tr) throw new Exception('操作失败');
                    if ($transfer_record['data_status'] == SellGoodsTransferRecord::DATA_STATUS_SUCCESS) {
                        $res_acc = SellGoodsAccountInfo::update(['total_income[-]' => $transfer_record['amount']], ['uid' => $transfer_record['uid']]);
                        if (!$res_acc) throw new Exception('操作失败');
                    }
                });
            } catch (Exception $exception) {
                return $this->response()->error($exception->getMessage());
            }
        } else {
            return $this->response()->error('撤销失败,请稍后重试o(TωT)o');
        }
        return $this->response()->success('撤销成功')->refresh();
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function dialog()
    {
        $this->confirm(self::TOAST_ALERT);
    }
}